package net.sppan.blog.controller.admin;

import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import net.sppan.blog.annotation.RequiresPermissions;
import net.sppan.blog.controller.BaseController;
import net.sppan.blog.model.Res;
import net.sppan.blog.model.RoleRes;
import net.sppan.blog.model.base.Condition;
import net.sppan.blog.model.base.Operators;
import net.sppan.blog.vo.ZtreeView;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

@RequiresPermissions(key={"admin:sys:res"})
public class AdminResController extends BaseController{
	@RequiresPermissions(key={"admin:sys:res:list"})
	public void list(){
		int pageNumber = getParaToInt("pageNumber", 1);
        int pageSize = getParaToInt("pageSize", 10);
        String search = getPara("search");
        Set<Condition> conditions=new HashSet<Condition>();
        LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
        orderby.put("seq", "asc");
        if(StrKit.notBlank(search)){
        	conditions.add(new Condition("name", Operators.LIKE, search));
        	setAttr("search", search);
        }
		Page<Res> page = Res.dao.getPage(pageNumber, pageSize, conditions, orderby);
		setAttr("pageList", page);
		render("list.html");
	}
	
	/**
	 * 获取Ztree树
	 */
	@Clear
	public void getZtreeViewList(){
		Integer type=this.getParaToInt("type");
		Integer roleId=this.getParaToInt("roleId");
		List<ZtreeView> list = Res.dao.getZtreeViewList(type, roleId);
		renderJson(list);
	}

	/**
	 * 跳转到表单页面
	 */
	@RequiresPermissions(key={"admin:sys:res:save"})
	public void add_edit(){
		Integer id = getParaToInt("id");
		if(id != null){
			Res res = Res.dao.findById(id);
			setAttr("res", res);
		}
		List<Res> menuTreeView = Res.dao.getMenuTreeView();
		setAttr("menuTreeView", menuTreeView);
		
		render("form.html");
	}
	
	/**
	 * 新增-更新资源
	 */
	@Before(EvictInterceptor.class)
	@CacheName("menu")
	@RequiresPermissions(key={"admin:sys:res:save"})
	public void save_update(){
		Res res = getModel(Res.class);
		res.setModifydate(new Date());
		if(res.getId() == null){
			renderJson(res.save(),"新增成功");
		}else{
			renderJson(res.update(),"编辑成功");
		}
	}
	
	/**
	 * 删除资源
	 */
	@Before(EvictInterceptor.class)
	@CacheName("menu")
	@RequiresPermissions(key={"admin:sys:res:delete"})
	public void delete(){
		Integer id = getParaToInt("id");
		boolean isSuccess  = false;
		Integer count = RoleRes.dao.deleteByResId(id);
		if (count != null && count >= 0) {
			isSuccess = Res.dao.deleteById(id);
			renderJson(isSuccess,"删除成功");
		}else{
			renderJson(isSuccess,"删除失败");
		}
	}
}
